package com.amigo.online.provider.user.config;

/**
 * @author pangdonghao
 * @version 1.0
 * @csdn https://blog.csdn.net/pangdongh
 * @createDate 2019/10/17 17:22
 */
import com.amigo.online.common.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.RequestFacade;
import org.springframework.util.StreamUtils;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.util.Enumeration;

/**
 * @author 01
 * @program wrapper-demo
 * @description 包装HttpServletRequest，目的是让其输入流可重复读
 * @create 2018-12-24 20:48
 * @since 1.0
 **/
@Slf4j
public class RequestWrapper extends HttpServletRequestWrapper {
    /**
     * 存储body数据的容器
     */
    private final byte[] body;

    public RequestWrapper(HttpServletRequest request) throws IOException {

        super(request);

        // 将body数据存储起来
        String bodyStr = getBodyString(request);
        body = bodyStr.getBytes(Charset.defaultCharset());
    }
    /**
     * 获取请求Body
     *
     * @param request
     * @return
     */
    public String getBodyString(final ServletRequest request) {
        String contentType = request.getContentType();
        String bodyString ="";

        if (StringUtils.isNotBlank(contentType) &&
                (contentType.contains("multipart/form-data") ||
                        contentType.contains("x-www-form-urlencoded"))){

            Enumeration<String> pars=request.getParameterNames();

            while(pars.hasMoreElements()){

                String n=pars.nextElement();
                bodyString+=n+"="+request.getParameter(n)+"&";
            }
            bodyString=bodyString.endsWith("&")?bodyString.substring(0, bodyString.length()-1):bodyString;
            return bodyString;
        }

        try {
            byte[] byteArray = StreamUtils.copyToByteArray(request.getInputStream());
            bodyString = new String(byteArray, "UTF-8");
        } catch (IOException e) {
        }

        return bodyString;
    }
//    /**
//     * 获取请求Body
//     *
//     * @param request request
//     * @return String
//     */
//    public String getBodyString(final ServletRequest request) {
//        try {
//            return inputStream2String(request.getInputStream());
//        } catch (IOException e) {
//            log.error("", e);
//            throw new RuntimeException(e);
//        }
//    }

    /**
     * 获取请求Body
     *
     * @return String
     */
    public String getBodyString() {
        final InputStream inputStream = new ByteArrayInputStream(body);

        return inputStream2String(inputStream);
    }

    /**
     * 将inputStream里的数据读取出来并转换成字符串
     *
     * @param inputStream inputStream
     * @return String
     */
    private String inputStream2String(InputStream inputStream) {
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = null;

        try {
            reader = new BufferedReader(new InputStreamReader(inputStream, Charset.defaultCharset()));
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            log.error("", e);
            throw new RuntimeException(e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    log.error("", e);
                }
            }
        }

        return sb.toString();
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    public void recycle(){
        if(this.getRequest() instanceof RequestFacade){
            try {
                Class requestFacade = RequestFacade.class;
                Field field = requestFacade.getDeclaredField("request");
                field.setAccessible(true);
                Request request = (Request) field.get(this.getRequest());
                field.setAccessible(false);

                Field inputStream = Request.class.getDeclaredField("inputStream");
                inputStream.setAccessible(true);
                inputStream.setAccessible(false);



            }  catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) {
        try {
            Class requestFacade = RequestFacade.class;
            Field field = requestFacade.getDeclaredField("request");

//            Request request = (Request) field.get(this.getRequest());
//            Field inputStream = Request.class.getField("inputStream");
//            inputStream.set(request, null);
//        }  catch (IllegalAccessException e) {
//            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {

        final ByteArrayInputStream inputStream = new ByteArrayInputStream(body);

        return new ServletInputStream() {
            @Override
            public int read() throws IOException {
                return inputStream.read();
            }

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {
            }
        };
    }
}
